package com.example.baseexercises.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: 辛之所想
 * @create: 2025-11-09 21:07
 * @description: 线程池练习
 **/
public class ThreadPoolExercises {
    public static void main(String[] args) {
        ThreadPoolExercises threadPoolExercises = new ThreadPoolExercises();
        threadPoolExercises.newFixedThreadPoolTest();
    }
    /**
     * 固定大小线程池 - 生成3个文件并等待所有任务完成
     */
    public void newFixedThreadPoolTest() {
        System.out.println("模拟批量生成文件开始");
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        String mktdId = "123456";
        // 提交3个文件生成任务
        for (int i = 1; i <= 3; i++) {
            final int fileNumber = i;
            threadPool.submit(() -> {
                try {
                    String fileName = "file_" + fileNumber + ".txt";
                    String content = "这是第 " + fileNumber + " 个文件，由线程 " + Thread.currentThread().getName() + " 生成";

                    // 模拟文件生成操作（这里可以替换为实际的文件写入逻辑）
                    System.out.println("正在生成文件: " + fileName);
                    Thread.sleep(1000); // 模拟耗时操作
                    switch (fileNumber) {
                        case 1:
                            test1(mktdId);
                            break;
                        case 2:
                            test2(mktdId);
                            break;
                        case 3:
                            test3(mktdId);
                            break;
                    }
                    System.out.println("文件生成完成: " + fileName + " - 内容: " + content);

                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.err.println("文件生成被中断: " + e.getMessage());
                }
            });
        }

        // 关闭线程池并等待所有任务完成
        threadPool.shutdown();

        try {
            // 等待所有任务完成，最多等待10分钟
            if (threadPool.awaitTermination(10, java.util.concurrent.TimeUnit.MINUTES)) {
                System.out.println("所有文件生成任务已完成，可以继续执行后续操作");
            } else {
                System.out.println("等待超时，但任务仍在执行中");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("等待任务完成时被中断: " + e.getMessage());
        }
    }
    public void test1(String mktId) {
        System.out.println(mktId +":test1");
    }
    public void test2(String mktId) {
        System.out.println(mktId +":test2");
        throw new RuntimeException("test2异常");
    }
    public void test3(String mktId) {
        System.out.println(mktId +":test3");
    }

}
